package les.anagrama.util;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Ranking {
	private static final int MAX_ROWS = 5;

	private Level level;
	private List<Score> scores;
	private RankingOpenHelper rankingOpenHelper;

	public Ranking(Context ctx) {
		rankingOpenHelper = new RankingOpenHelper(ctx);
	}

	public List<Score> getScores(Level level) {
		if (this.level == level && scores != null) {
			return scores;
		}

		SQLiteDatabase database = rankingOpenHelper.getReadableDatabase();
		Cursor query = database.query("ranking", new String[] { "player",
				"score", "level" }, "level = ?",
				new String[] { "" + level.ordinal() }, null, null,
				"score DESC", "0, " + MAX_ROWS);

		this.level = level;
		scores = new ArrayList<Score>(MAX_ROWS);
		while (!query.isLast() && !query.isAfterLast()) {
			query.moveToNext();
			scores.add(new Score(query.getString(0), query.getInt(1), Level
					.values()[query.getInt(2)]));
		}

		query.close();
		database.close();

		return scores;
	}

	public boolean addScore(Score score) {
		ContentValues value = new ContentValues();
		value.put("player", score.getPlayer());
		value.put("score", score.getScore());
		value.put("level", score.getLevel().ordinal());

		SQLiteDatabase database = rankingOpenHelper.getWritableDatabase();
		database.insert("ranking", null, value);
		database.close();

		scores = null;

		return getScores(score.getLevel()).contains(score);
	}

	private class RankingOpenHelper extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "anagrama";
		private static final int DATABASE_VERSION = 2;
		private static final String TABLE_NAME = "ranking";

		public RankingOpenHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + TABLE_NAME
					+ " (player TEXT, score INTEGER, level INTEGER);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
	}
}
